const fs = require('fs');
const { get } = require('koa/lib/response');
const router = require('koa-router')();


function routerFile(filePath) {


    let Files = fs.readdirSync(filePath)//读取router文件夹下的所有文件

    let routerFiles = Files.filter(item => {
        return item.endsWith('.js') && item !== 'index.js'
        //过滤以js结尾且index文件
    })
    return routerFiles
}


function regRoute(routerFiles) {

    routerFiles.forEach(item => {

        let tmpPath = __dirname + '/' + item
        let obj = require(tmpPath)

        for (let key in obj) {
/*             console.log('我是key：' + key);
            console.log('我是obj：' + obj);
            console.log('我是keyObj：' + obj[key]); */

            let temArr=key.split(' ')
           /*  console.log(temArr); */
            let rPath = temArr[1]; //路径
            let rmethod=temArr[0]; //方法
            let rObjfn = obj[key];

            if(rmethod=='get'){
                /* console.log('yes'); */
                router.get(rPath, rObjfn)
            }else if(rmethod=='post'){
                router.post(rPath, rObjfn)
            }else if(rmethod=='put'){
                router.put(rPath, rObjfn)
            }else if(rmethod=='delete'){
                console.log('yes');
                console.log(rObjfn);
                router.delete(rPath, rObjfn)
            }else{
                console.log('没有找到方法');
            }


        }
    });

    return router.routes();
}





module.exports = function () {
    let routerFiles = routerFile(__dirname);
    let fn= regRoute(routerFiles);
    return fn;
};